'use strict';

let { Products, Op } = require('../model');

let fn_lllll = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    console.log(keyword.length);
    if (keyword) {
        let list;
        list = await Products.findAll({
            where: {
                [Op.or]: [
                    { StudentName: keyword },
                    { Studentclass: keyword },
                    { Studentipone: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { Studentaddress: keyword },
                ]
            },
            order:['id']
        })
        ctx.body = {
            code: 1000,
            data: list,
            msg: '请求成功'
        }
    } else {
        let list = await Products.findAll({
            order:['id']
        });
        ctx.body = {
            code: 900,
            data: list,
            msg: '失败'
        }
    }
}
let fn_getbyid = async (ctx, next) => {
    let id = ctx.request.params.id;
    let product = await Products.findByPk(id);
    if (product) {
        ctx.body = {
            code: 1000,
            data: product,
            msg: '获取成功'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: '不好意思不存在'
        }
    }
}
let fn_post =async (ctx, next) => {
    let obj = ctx.request.body;
    console.log(obj);

    await Products.create(obj);
    ctx.body = obj;
}
let fu_Edit =async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let product = await Products.findByPk(id);
    
    if (product) {
        Products.update(obj,{
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: product,
            msg: '修改成功'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: '商品不存在'
        }
    }
}
let fn_delete =async (ctx, next) => {
    let id = ctx.request.params.id;
    console.log(id);
    let product = await Products.findByPk(id);
    if (product) {
        Products.destroy({
            where:{
                id:id
            }
        })
        ctx.body = {
            code: 1000,
            data: { id },
            msg: '删除成功'
        }
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '不存在，请重试。'
        }
    }
}

module.exports = {
    'get /product': fn_lllll,
    'get /product/:id': fn_getbyid,
    'post /product': fn_post,
    'put /product/:id': fu_Edit,
    'delete /product/:id': fn_delete
}